//
//  EBAPIService.swift
//  Networking
//
//  Created by 许必成 on 2020/7/22.
//  Copyright © 2020年 东信北邮信息技术有限公司. All rights reserved.
//

import HandyJSON
import Moya

extension Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) throws -> T {
        let jsonString = String(data: data, encoding: .utf8)
        guard let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) else {
            throw MoyaError.jsonMapping(self)
        }
        return model
    }
}

extension MoyaProvider {
    @discardableResult
    open func request<T: HandyJSON>(_ target: Target,
                                    model: T.Type,
                                    completion: @escaping (T?, Bool) -> Void) -> Cancellable? {
        
        
        return request(target, completion: { result in
            
            switch result {
            
            case let .success(moyaResponse):
                let data = moyaResponse.data
                
                let jsonString = String(data: data, encoding: .utf8)
                print("\(jsonString)")
                if T.self == GZStringModel.self {
                    
                    let str = String(data: data, encoding: .utf8)
                    let model = GZStringModel()
                    let ss = str?.replacingOccurrences(of: "\"", with: "")
                    model.message = ss
                    completion(model as? T, true)
                    return
                }
                
                if(moyaResponse.statusCode == 401){
                    
                    let alertController = UIAlertController(title: "系统提示",
                                    message: "异常登录", preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "确定", style: .default, handler: {
                        action in
                        
                        appdelegate().loginSence()
                    })
                    alertController.addAction(okAction)
                    currentViewController()?.present(alertController, animated: true, completion: nil)
                    
                    return
                }
                
                
                guard let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) else {
                    
                    if(!self.successStatus(code: moyaResponse.statusCode)){
     
                        
                        completion(nil, false)
                        return
                    }else{
                        
                        let model = BaseModel()
                        model.message  = "成功"
                        completion(model as? T, true)
                        return
                    }
                }
                completion(model, true)
                
            case let .failure(error):
                let _ = NSError(domain: "EBAPIService.error", code: 2, userInfo: [NSLocalizedDescriptionKey: error.localizedDescription])
                completion(nil, false)
            }

        })
    }
    func successStatus(code: Int) -> Bool {
        return [200, 201, 202, 203, 204].contains(code)
    }

}


struct returnData<T: HandyJSON>: HandyJSON {
    var status: Int = 0
    var msg:String?
    var result: T?
}
struct ModelData: HandyJSON {}
extension Array: HandyJSON{}

